const express = require('express');//引入express
const router = express.Router();//引入express路由
const DB = require('../db/db');//引入数据库
const sms_util = require('../common/sms_util');
const md5 = require('blueimp-md5');

let users = {}; // 用户信息

router.get('/', function(req, res, next) {
  res.render('index', { title: '我是users路由' });
});

/*
  发送验证码短信
*/
router.get('/api/send_code', (req, res) => {
    // 1. 获取手机号码
    let phone = req.query.phone;

    // 2. 随机产生验证码
    let code = sms_util.randomCode(6);
	// req.session.code = code;
	console.log(req.session)
    // console.log(code);

    /* sms_util.sendCode(phone, code, function (success) {
        if (success) {
             users[phone] = code;
             res.json({success_code: 200, message: '验证码获取成功!'});
         } else {
             res.json({err_code: 0, message: '验证码获取失败!'});
         }
     });*/
		// 成功
		setTimeout(()=>{
			users[code] = code
			res.json({success_code: 200, message: code});
		},2000)
});
/**
 * 注册新用户
 */
router.post('/api/addRegister',async (req, res) => {
	console.log(req.body)
	let data = JSON.parse(req.body.data)
	let {phone, code, password} = data
	let content = [];
	//是否存在该用户
	let sql = "SELECT * FROM user_info WHERE user_phone = '" + phone + "' LIMIT 1";
	let results = await DB.query(sql,content);
	if(results.length == 0){
		//插入sql语句
		let sql = "INSERT INTO user_info(user_phone, user_name, user_pwd) VALUES (?, ?, ?)";
		content = [phone, phone, md5(password)];
		let results = await DB.query(sql,content);	
		//返回数据
		res.json({err_code: 0, message: '注册成功'});
	}else{
		res.json({err_code: 0, message: '该用户已经注册'});
	}
})
/**
 * 用户登录
 */
router.post('/api/doLogin',async (req, res) => {
	console.log(req.body)
	// 1. 获取数据
	let data = JSON.parse(req.body.data)
	let {phone, code, password, isLoginWay} = data
	console.log(password)
	let content = [];
	//验证码登录
	if(isLoginWay){
		// 2. 验证验证码是否正确
		if (users[code] !== code) {
			res.json({err_code: 0, message: '验证码不正确!'});
		}
		// 3. 查询数据
		delete  users[code];
		let sql = "SELECT * FROM user_info WHERE user_phone = '" + phone + "' LIMIT 1";
		let results = await DB.query(sql,content);
			results = JSON.parse(JSON.stringify(results));
			console.log(results)
		if(results[0]){
			// console.log(results[0]);
			req.session.userId = results[0].id;
			// 返回数据给客户端
			res.json(results);
		} else { // 新用户
			res.json({err_code: 0, message: '请先注册再登录!'});
			return;
		}
	}else{//手机号码、密码登录
		// 2. 查询数据
		let sql = "SELECT * FROM user_info WHERE user_phone = '" + phone + "' LIMIT 1";
		let results = await DB.query(sql,content);
		results = JSON.parse(JSON.stringify(results));
		console.log(results)
		if(results[0]){
			// 验证密码是否正确
			if (results[0].user_pwd !== md5(password)) {
				res.json({err_code: 0, message: '密码不正确!'});
			} else {
				req.session.userId = results[0].id;
				// 返回数据给客户端
				res.json(results);
			}
		} else { // 新用户
			res.json({err_code: 0, message: '请先注册再登录!'});
			return;
		}
	}
})

module.exports = router;
